package com.example.androidautoproject.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.accessibilityservice.GestureDescription
import android.content.Intent
import android.graphics.Path
import android.graphics.Point
import android.os.Build
import android.os.Handler
import android.util.Log
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Toast
import com.example.androidautoproject.utils.NodePrinter
import com.example.androidautoproject.utils.PrefsManager

class MyAccessibilityServiceNew: AccessibilityService() {
    private val TAG  = "AccessibilityService"
    private var operationPerformed = false

    override fun onServiceConnected() {
        super.onServiceConnected()
        Log.d(TAG, "无障碍服务已连接")
        Toast.makeText(this, "无障碍服务已启动", Toast.LENGTH_SHORT).show()
        // 动态配置服务
        configureService()
    }

    private fun configureService(){
        try {
            val info = serviceInfo
            info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK
            info.packageNames = arrayOf(PrefsManager.getPackageName(this))
            info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK
            info.notificationTimeout = 0
            info.flags = AccessibilityServiceInfo.DEFAULT or
                    AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or
                    AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS or
                    AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
            serviceInfo = info
            Log.d(TAG, "服务配置更新完成")
        } catch (e:Exception){
            Log.e(TAG, "配置服务时出错: ${e.message}")
        }
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        if (operationPerformed) return
        Log.d(TAG, "接收到无障碍事件: ${event.eventTypeToString()}")
        Log.d(TAG, "包名: ${event.packageName}, 类名: ${event.className}")
        // 获取当前配置的目标包名和标识
        val targetPackage = PrefsManager.getPackageName(this)
        val screenIdentifier = PrefsManager.getScreenIdentifier(this)
        // 检查是否是目标应用的事件
        if (event.packageName?.toString() != targetPackage) return


        when (event.eventType) {
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                Log.d(TAG, "窗口状态变化")
                // 检查类名是否包含标识
                if (event.className?.contains(screenIdentifier, true) == true) {
                    Log.d(TAG, "检测到目标界面: ${event.className}")
                }
            }
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {
                Log.d(TAG, "窗口内容变化")
                Thread.sleep(10000)
                // 尝试查找特定元素来确认页面加载完成
                val rootNode = rootInActiveWindow ?: return
//                var targetNodes = rootNode.findAccessibilityNodeInfosByText("任务")
//                targetNodes.forEach{
//                    clickNode(it)
//                }
                clickAtPosition(this, 200.toFloat(), 500.toFloat())
                operationPerformed = true
                Log.d(TAG, "任务执行完毕")
//                if(printTargetNodes(targetNodes, rootNode)){
//                    for (node in targetNodes) {
//                        Log.d(TAG, "节点是否可以点击${node.isVisibleToUser}")
//                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
//                        operationPerformed = true
//                    }
//                }

            }
            AccessibilityEvent.TYPE_VIEW_SCROLLED -> {
                // 可以监听滚动事件
            }
            else -> {
                Log.d(TAG, "其他类型事件: ${event.eventType}")
            }
        }
    }

    private fun printTargetNodes(targetNodes: List<AccessibilityNodeInfo>, rootNode: AccessibilityNodeInfo):Boolean{
        if (targetNodes.isEmpty()) {
            Log.d(TAG, "未找到包含任务文本的节点")
            return false
        } else {
            try {
                Log.d(TAG, "找到 ${targetNodes.size} 个匹配节点")
                // 打印节点信息
                NodePrinter.printNodeInfo(targetNodes, "NodeInfo")
                // 回收节点
                targetNodes.forEach { it.recycle() }
            } finally {
                rootNode.recycle()
            }
            return true
        }
    }

    private fun performSwipeAfterDelay(delay: Long) {
        // operationPerformed = true
        Handler(mainLooper).postDelayed({
            // 等待界面完全加载（根据实际情况调整）
            // Thread.sleep(1000)
            performSwipe()
        }, delay)
    }

    override fun onInterrupt() {
        Log.w(TAG, "无障碍服务被中断")
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.d(TAG, "服务解除绑定")
        operationPerformed = false // 重置状态
        return super.onUnbind(intent)
    }

    // 将事件类型转换为可读字符串
    private fun AccessibilityEvent.eventTypeToString(): String {
        return when (this.eventType) {
            AccessibilityEvent.TYPE_VIEW_CLICKED -> "VIEW_CLICKED"
            AccessibilityEvent.TYPE_VIEW_LONG_CLICKED -> "VIEW_LONG_CLICKED"
            AccessibilityEvent.TYPE_VIEW_SELECTED -> "VIEW_SELECTED"
            AccessibilityEvent.TYPE_VIEW_FOCUSED -> "VIEW_FOCUSED"
            AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED -> "VIEW_TEXT_CHANGED"
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> "WINDOW_STATE_CHANGED"
            AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED -> "NOTIFICATION_STATE_CHANGED"
            AccessibilityEvent.TYPE_VIEW_HOVER_ENTER -> "VIEW_HOVER_ENTER"
            AccessibilityEvent.TYPE_VIEW_HOVER_EXIT -> "VIEW_HOVER_EXIT"
            AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START -> "TOUCH_EXPLORATION_START"
            AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END -> "TOUCH_EXPLORATION_END"
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> "WINDOW_CONTENT_CHANGED"
            AccessibilityEvent.TYPE_VIEW_SCROLLED -> "VIEW_SCROLLED"
            AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED -> "TEXT_SELECTION_CHANGED"
            else -> "UNKNOWN: ${this.eventType}"
        }
    }

    fun clickAtPosition(service: AccessibilityService, x: Float, y: Float) {
        val gestureBuilder = GestureDescription.Builder()
        val clickPath = Path().apply {
            moveTo(x, y)
        }

        val clickGesture = gestureBuilder
            .addStroke(
                GestureDescription.StrokeDescription(
                clickPath,
                0,
                1 // 持续时间非常短，模拟点击
            ))
            .build()

        service.dispatchGesture(clickGesture, null, null)
    }

    fun clickNode(node: AccessibilityNodeInfo?) {
        node?.let {
            if (it.isClickable) {
                it.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            } else {
                // 如果节点不可点击，尝试查找可点击的父节点
                var parent = it.parent
                while (parent != null) {
                    if (parent.isClickable) {
                        parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        parent.recycle()
                        break
                    }
                    val temp = parent
                    parent = parent.parent
                    temp.recycle()
                }
            }
            it.recycle()
        }
    }





    private fun performSwipe() {
        Log.d(TAG, "Performing swipe")

        // 等待目标应用加载
        Thread.sleep(2000)

        // 获取屏幕尺寸（兼容所有API版本）
        val screenSize = getScreenSize()
        val width = screenSize.x
        val height = screenSize.y

        if (width == 0 || height == 0) {
            Log.e(TAG, "Failed to get screen size")
            Toast.makeText(this, "无法获取屏幕尺寸", Toast.LENGTH_SHORT).show()
            return
        }

        Log.d(TAG, "Screen size: ${width}x${height}")

        // 创建滑动手势（从底部滑动到顶部）
        val path = Path().apply {
            moveTo(width / 2f, height * 0.8f)  // 起始点（屏幕底部）
            lineTo(width / 2f, height * 0.2f)  // 结束点（屏幕顶部）
        }

        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 500))
            .build()

        // 执行手势
        dispatchGesture(gesture, object : GestureResultCallback() {
            override fun onCompleted(gestureDescription: GestureDescription?) {
                super.onCompleted(gestureDescription)
                Log.d(TAG, "Swipe completed")
                Toast.makeText(
                    this@MyAccessibilityServiceNew,
                    "滑动操作完成",
                    Toast.LENGTH_SHORT
                ).show()
            }

            override fun onCancelled(gestureDescription: GestureDescription?) {
                super.onCancelled(gestureDescription)
                Log.w(TAG, "Swipe cancelled")
                Toast.makeText(
                    this@MyAccessibilityServiceNew,
                    "滑动操作取消",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }, null)
    }

    // 兼容所有API版本的屏幕尺寸获取方法
    private fun getScreenSize(): Point {
        val size = Point()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11+ 方法
            val display = display
            display?.getRealSize(size)
        } else {
            // 旧版Android方法
            val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            val display = windowManager.defaultDisplay

            @Suppress("DEPRECATION")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                // API 17+ 方法
                display.getRealSize(size)
            } else {
                // 最旧方法 (API < 17)
                @Suppress("DEPRECATION")
                display.getSize(size)
            }
        }

        // 如果获取失败，使用DisplayMetrics作为后备
        if (size.x == 0 || size.y == 0) {
//            val metrics = DisplayMetrics()
//            windowManager.defaultDisplay.getMetrics(metrics)
//            size.set(metrics.widthPixels, metrics.heightPixels)
        }

        return size
    }
}